<template>
	<view class="preview">
		<swiper circular :current="currentIndex" @change="swiperChange">
			<swiper-item v-for="(item,index) in detailInfoList" :key="item._id" >
				<image v-if="loadedIndexList.includes(index)" @click="maskShowHide()" :src="item.smallPicurl" mode="aspectFill"></image>
			</swiper-item>
		</swiper>
		<view class="mask" v-show="maskFlag">
			<view class="goBack" @click="goBack" :style="{top:(getStatusBarHeight() || 15) +'px'}">
				<uni-icons type="left" size="20" color="#fff"></uni-icons>
			</view>
			<view class="count">{{currentIndex + 1}} / {{detailInfoList.length}}</view>
			<view class="time">
				<uni-dateformat format="hh:mm" :date="nowDatetime"></uni-dateformat>
			</view>
			<view class="date" >
				<uni-dateformat format="MM月dd日" :date="nowDatetime"></uni-dateformat>
			</view>
			<view class="footer">
				<view class="box" @click="infoShowHide()">
					<uni-icons type="info" size="28"></uni-icons>
					<view class="info">信息</view>
				</view>
				<view class="box" @click="rankShowHide()">
					<uni-icons type="star" size="28"></uni-icons>
					<view class="info">评分</view>
				</view>
				<view class="box">
					<uni-icons type="download" size="23" @click="downloadImg"></uni-icons>
					<view class="info">下载</view>
				</view>
			</view>
		</view>
		<!-- 图片信息弹框 -->
		<uni-popup ref="infoPop" type="bottom" :safe-area="false">
			<view class="infoPop">
				<view class="popHeader">
					<view></view>
					<view class="title">壁纸信息</view>
					<view class="close" @click="closeInfoPop()">
						<uni-icons type="closeempty" size="18" color="#999"></uni-icons>
					</view>
				</view>
				<scroll-view scroll-y>
					<view class="content" v-if="currentDetailInfo">
						<view class="row">
							<view class="label">壁纸ID:</view>
							<text selectable>{{currentDetailInfo?._id}}</text>
						</view>
						<view class="row">
							<view class="label">发布者:</view>
							<text>{{currentDetailInfo?.nickname}}</text>
						</view>
						<view class="row">
							<view class="label">评分:</view>
							<view class="infoScore">
								<uni-rate class="rankStar" readonly allow-half :value="currentDetailInfo?.score" />
								<view>{{currentDetailInfo?.score}}分</view>
							</view>
						</view>
						<view class="row">
							<view class="label">摘要:</view>
							<text selectable>{{currentDetailInfo?.description}}</text>
						</view>
						<view class="row">
							<view class="label">标签:</view>
							<view class="tag-view" v-for="(item,index) in currentDetailInfo?.tabs" :key="index">
								<uni-tag inverted circle :text="item" type="success" />
							</view>
						</view>
						<view class="desc">
							声明：本图片来自用户投稿，非商业使用，用于免费学习交流，如侵犯了您的权益，您可以拷贝壁纸ID举报至平台，就安阿八八八八八
						</view>
					</view>
				</scroll-view>
			</view>
		</uni-popup>
		<!-- 评分弹框 -->
		<uni-popup ref="rankPop" type="center" :is-mask-click="false">
			<view class="rankPop">
				<view class="rankHeader">
					<view></view>
					<view class="title" v-show="!isRanked">壁纸评分</view>
					<view class="title" v-show="isRanked">我的评分</view>
					<view class="close" @click="closeRankPop()">
						<uni-icons type="closeempty" size="18" color="#999"></uni-icons>
					</view>
				</view>
				<view class="content">
					<view class="row">
						<view class="label">评分:</view>
						<view class="infoScore">
							<uni-rate class="rankStar" allow-half :value="rankStar" @change="rankChange"/>
							<view>{{rankStar}}分</view>
						</view>
					</view>
					<view class="footer" v-show="!isRanked">
						<button :disabled="disableSubmit" class="rankSubmit" type="default" size="mini" plain @click="submitRank()">提交</button>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>
<script setup>
import {onLoad} from "@dcloudio/uni-app";
import { apiDetailWall } from '../../api/apis';
import { ref, watch, watchEffect} from 'vue';
import {getStatusBarHeight} from '../../utils/systemInfo.js';

onLoad( (e) => {
	// 从缓存获取图片列表
	getDetailWall(e.id,e.fromHome)
});
// 图片列表
const detailInfoList = ref([]);
// 当前图片详情对象
const currentDetailInfo = ref(null);
// 当前索引
const currentIndex = ref(0);
// 加载过的图片索引集合
let loadedIndexList = ref([]);

// 初始化获取图片列表
const getDetailWall = async (id,fromHome) => {
	let wallPaperList = []
	// 如果是从首页跳转，直接查看图片详情
	if(fromHome) {
		let res = await apiDetailWall({id: id})
		wallPaperList = res.data;
	}else {		
		wallPaperList = uni.getStorageSync("wallPaperList")
	}
	detailInfoList.value = wallPaperList.map(m => {
		m.smallPicurl = m.smallPicurl.replace("_small.webp",".jpg")
		return m
	})
	// 获取当前图片索引
	currentIndex.value = detailInfoList.value.findIndex(f => f._id == id)
	// 当前图片详情
	currentDetailInfo.value = detailInfoList.value[currentIndex.value]
	// 图片懒加载
	lazyLoadIndexList(currentIndex.value)
}

// 图片懒加载历史索引
const lazyLoadIndexList = (index) => {
	loadedIndexList.value.push(
		index == 0 ? detailInfoList.value.length - 1 : index - 1,
		index,
		index == detailInfoList.value.length -1 ? 0 : index + 1
	)
	loadedIndexList.value = [...new Set(loadedIndexList.value)]
}


// 轮播图change事件
const swiperChange = (e) => {
	currentIndex.value = e.detail.current
	currentDetailInfo.value = detailInfoList.value[currentIndex.value]
	// 图片懒加载
	lazyLoadIndexList(currentIndex.value)
}

// 点击图片显隐遮罩
const maskFlag = ref(true);
const maskShowHide = () => {
	maskFlag.value = !maskFlag.value
}

// 实时日期
const nowDatetime = ref(Date.now());
setInterval(() => {nowDatetime.value = Date.now()},1000)

// 点击展示图片信息弹框
const infoPop = ref(null) // 变量名和组件的ref名一样可以拿到组件，等同vue2的 this.$refs.infoPop
const infoShowHide = () => {
	infoPop.value.open();
}
const closeInfoPop = () => {
	infoPop.value.close();
}

// 评分弹框
const rankPop = ref(null);
// 我的评分
const rankStar = ref(0);
// 是否评分过
const isRanked = ref(false);
// 分数为0 提交按钮禁用
const disableSubmit = ref(true);
watch(rankStar, (newX) => {
  if(newX > 0) {
  	disableSubmit.value = false;
  }else {
  	disableSubmit.value = true;
  }
});
// 打开弹窗
const rankShowHide = () => {
	// 获取缓存中用户评分（实际应该调用后端接口获取评分）
	let rankedList = uni.getStorageSync("rankedList") || []
	isRanked.value = rankedList.map(m => m.id).includes(currentDetailInfo.value._id)
	rankStar.value = rankedList.filter(f => f.id ==  currentDetailInfo.value._id).map(m => m.rank)[0] || 0
	rankPop.value.open();
}
// 关闭弹窗
const closeRankPop = () => {
	rankPop.value.close();
}
// 评分change事件
const rankChange = (e) => {
	rankStar.value = e.value;
}
// 提交评分
const submitRank = () => {
	// 记录本地已打过分的壁纸信息（其实应该后端判断）
	let rankedList = uni.getStorageSync("rankedList") || []
	if(isRanked.value) {
		uni.showToast({
			title:"你已经评分过了",
			icon: "none"
		})
		return ;
	}
	console.log("提交成功",rankStar.value)
	uni.showToast({
		title:"评分成功",
		icon: "none"
	})
	rankedList.push({id: currentDetailInfo.value._id, rank: rankStar.value})
	closeRankPop();
	uni.setStorageSync("rankedList",rankedList)
}

// 返回上一页
const goBack = () => {
	uni.navigateBack();
}

// 下载图片
const downloadImg = () => {
	// #ifdef H5
	uni.showToast({
		title:"长按壁纸即可下载",
		icon: "none"
	})
	return;
	// #endif
	
	// #ifndef H5
	uni.showLoading({
		title:"加载中"
	})
	uni.getImageInfo({
		src: currentDetailInfo.value.smallPicurl,
		success: (res) => {
			uni.saveImageToPhotosAlbum({
				filePath:res.path,
				success() {
					uni.showToast({
						title:"保存成功",
						icon: "none"
					})
				},
				fail: (err) => {
					if(err.Msg == "saveImageToPhotosALbum:fail cancel") {
						uni.showToast({
							title: "保存失败",
							icon: "none"
						})
						return;
					}
					uni.showModal({
						title:"提示",
						content:"需要授权保存相册",
						success: res => {
							if(res.confirm) {
								uni.openSetting({
									success: (setting) => {
										if(setting.authSetting['scope.writePhotosAlbum']) {
											uni.showToast({
												title: "获取授权成功",
												icon: "none",
											})
										}else {
											uni.showToast({
												title: "获取授权失败",
												icon: "none"
											})
										}
									}
								})
							}
						}
					})
				}
			})
		},
		complete() {
			uni.hideLoading()
		}
	})
	// #endif
}
</script>

<style lang="scss" scoped>
.preview {
	width: 100%;
	height: 100vh;
	position: relative;
	swiper{
		width: 100%;
		height: 100%;
		image {
			width: 100%;
			height: 100%;
		}
	}
	.mask {
		&>view {
			position: absolute;
			left: 0;
			right: 0;
			width: fit-content;
			margin: auto;
			color: #fff;
		}
		.goBack {
			position: absolute;
			border-radius: 50%;
			padding: 10rpx;
			top:0;
			left: -600rpx;
			background-color: rgba(0, 0, 0, 0.3);
			backdrop-filter: blur(10rpx);
		}
		.count {
			top: 10vh;
			color: #fff;
			font-size: 28rpx;
			color: #fff;
			border-radius: 40rpx;
			padding: 8rpx 28rpx;
			background-color: rgba(0, 0, 0, 0.3);
			backdrop-filter: blur(10rpx);
		}
		.time {
			top: calc(10vh + 80rpx);
			font-size: 140rpx;
			font-weight: 200;
			line-height: 1em;
			text-shadow: 0 4rpx rgba(0, 0, 0, 0.3);
		}
		.date {
			top: calc(10vh + 230rpx);
			font-size: 34rpx;
			font-weight: 200;
			line-height: 1em;
			text-shadow: 0 4rpx rgba(0, 0, 0, 0.3);
		}
		.footer {
			background:rgba(255, 255, 255, 0.8);
			bottom: 10vh;
			width: 65vw;
			height: 120rpx;
			border-radius: 120rpx;
			color: #000;
			display: flex;
			justify-content: space-around;
			align-items: center;
			box-shadow: 0 2rpx 0 rgba(0, 0, 0, 0.1);
			backdrop-filter: blur(20rpx);
			.box {
				display: flex;
				flex-direction: column;
				padding: 2rpx 12rpx;
				.info {
					font-size: 26rpx;
					color: $text-font-color-2;
				}
			}
		}
	}
	.infoPop {
		background-color: #fff;
		padding: 30rpx;
		padding-bottom: 90rpx;
		border-radius: 30rpx 30rpx 0 0 ;
		overflow: hidden;
		.popHeader {
			display: flex;
			justify-content: space-between;
			align-items: center;
			.title {
				font-size: 28rpx;
				color: $text-font-color-2;
			}
			.close {
				padding: 6rpx;
			}
		}
		scroll-view {
			max-height: 60vh;
			.content {
				.row {
					padding: 16rpx 0;
					font-size: 32rpx;
					line-height: 1.7em;
					display: flex;
					.label {
						width: 140rpx;
						text-align: right;
						font-size: 30rpx;
						color: $text-font-color-3;
						margin-right: 20rpx;
					}
					text {
						flex: 1;
						width: 0;
					}
					.type {
						color: $brand-theme-color;
					}
					.infoScore {
						display: flex;
						.rankStar {
							margin-right: 10rpx;
						}
					}
					.tag-view {
						margin: 0 5rpx;
					}
				}
				.desc {
					margin-top: 20rpx;
					background-color: #f6f6f6;
					padding: 20rpx;
					font-size: 28rpx;
					color: $text-font-color-2;
				}
			}
		}
	}
	.rankPop {
		width: 600rpx;
		background-color: #fff;
		padding: 30rpx;
		border-radius: 30rpx;
		overflow: hidden;
		.rankHeader {
			display: flex;
			justify-content: space-between;
			.title {
				font-size: 28rpx;
				color: $text-font-color-2;
			}
			.close {
				padding: 6rpx;
			}
		}
		.content {
			.row {				
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 16rpx 0;
				font-size: 32rpx;
				line-height: 1.7em;
				display: flex;
			}
			.infoScore {
				display: flex;
				.rankStar {
					margin-right: 10rpx;
				}
			}
			.footer {
				display: flex;
				align-items: center;
				justify-content: center;
				.rankSubmit {
					padding: 5rpx 100rpx;
				}
			}
		}
		
	}
}
</style>
